package lol.clann.bukkit.pluginboot.config.jackson.item;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import lol.clann.bukkit.pluginboot.util.ItemStackUtils;
import lol.clann.clannboot.annotation.inject.Inject;
import lol.clann.clannboot.annotation.svc.PostInstance;
import lol.clann.clannboot.annotation.svc.Service;
import lol.clann.clannboot.config.jackson.Jackson;
import org.bukkit.inventory.ItemStack;

import java.io.IOException;

/**
 * @author pyz
 * @date 2018/10/12 下午8:14
 */
@Service(priority = Integer.MAX_VALUE - 100)
public class ItemStackSerializer {

    @Inject
    private ItemStackUtils itemStackUtils;

    @PostInstance
    private void init() {
        Jackson.addSerializer(ItemStackUtils.classNMSItemStack.getHandle(), new JsonSerializer<Object>() {
            @Override
            public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
                Object tag = itemStackUtils.toCompound(value);
                gen.writeObject(tag);
            }
        });
        Jackson.addSerializer(ItemStack.class, new JsonSerializer<ItemStack>() {
            @Override
            public void serialize(ItemStack value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
                Object tag = itemStackUtils.toCompound(value);
                gen.writeObject(tag);
            }
        });
    }
}
